package com.bocom.hairy.crab.consumer.interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpStatusCodeException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 自定义响应错误处理器
 * 将HTTP错误状态码（4xx/5xx）转换为自定义异常
 */
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = (HttpStatus) response.getStatusCode();

        // 处理4xx客户端错误
        if (statusCode.is4xxClientError()) {
            String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
            throw new HttpClientException(
                    "客户端错误: " + statusCode.value() + " " + statusCode.getReasonPhrase(),
                    statusCode.value(),
                    responseBody
            );
        }

        // 处理5xx服务器错误
        if (statusCode.is5xxServerError()) {
            String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
            throw new HttpServerException(
                    "服务器错误: " + statusCode.value() + " " + statusCode.getReasonPhrase(),
                    statusCode.value(),
                    responseBody
            );
        }

        // 其他错误使用默认处理
        super.handleError(response);
    }

    // 自定义异常类
    public static class HttpClientException extends RuntimeException {
        private final int statusCode;
        private final String responseBody;

        public HttpClientException(String message, int statusCode, String responseBody) {
            super(message);
            this.statusCode = statusCode;
            this.responseBody = responseBody;
        }

        // getter方法
        public int getStatusCode() { return statusCode; }
        public String getResponseBody() { return responseBody; }
    }

    public static class HttpServerException extends RuntimeException {
        private final int statusCode;
        private final String responseBody;

        public HttpServerException(String message, int statusCode, String responseBody) {
            super(message);
            this.statusCode = statusCode;
            this.responseBody = responseBody;
        }

        // getter方法
        public int getStatusCode() { return statusCode; }
        public String getResponseBody() { return responseBody; }
    }
}

